<template>
  <section>
    <h2>computed</h2>
    <div>
      firstName: <input type="text" v-model="first_name" /> lastName:
      <input type="text" v-model="last_name" />
    </div>
    <div>姓名：<input type="text" v-model="name" /></div>
    <p>全名（外国习惯）: {{ full_name }}</p>
    <p>全名（中国习惯）: {{ chinese_name }}</p>
  </section>
</template>

<script lang="ts">
import { computed, ref } from "vue";

export default {
  setup() {
    const first_name = ref("Hydra");
    const last_name = ref("Feng");

    const full_name = computed(() => {
      return first_name.value + " " + last_name.value;
    });

    const chinese_name = computed(() => {
      return last_name.value + " " + first_name.value;
    });

    // 如果要给computed属性加上setter，参数变为对象
    const name = computed<string>({
      set(val:string) {
        // 使用空格拆分
        const arr = val.split(" ");
        first_name.value = arr[0]; 
        if (arr[1]) {
            last_name.value = arr[1];
        }
      },
      get():string {
        return first_name.value + " " + last_name.value;
      },
    });

    return {
      full_name,
      first_name,
      last_name,
      chinese_name,
      name
    };
  },
};
</script>

<style>
</style>